package com.hyfd.deal.Flow;

import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.hyfd.common.GenerateData;
import com.hyfd.common.utils.Base64Utils;
import com.hyfd.common.utils.JsonHelper;
import com.hyfd.common.utils.MapUtils;
import com.hyfd.common.utils.PostUtil;
import com.hyfd.common.utils.PublicRSA;
import com.hyfd.common.utils.Sign;
import com.hyfd.common.utils.ToolDateTime;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.deal.BaseDeal;

/**
 * 菠萝蜜单号码流量充值接口
 * 
 * @author cxj
 *
 */
public class HuaGuFlowDeal implements BaseDeal
{
    Logger log = Logger.getLogger(getClass());
    
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> deal(Map<String, Object> order)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        int flag = -1;
        
        try
        {
            // 手机号
            String mobile = (String)order.get("phone");
            // 平台订单号
            String c_id = ToolDateTime.format(new Date(), "yyyyMMddHHmmssSSS") + mobile + GenerateData.getIntData(9, 4);
            map.put("orderId", c_id);
            String p_id = (String)order.get("providerProductId");//产品id
            // 账号
            Map<String, Object> channel = (Map<String, Object>)order.get("channel");// 获取通道参数
            String linkUrl = (String)channel.get("link_url");// 充值地址
            String defaultParameter = (String)channel.get("default_parameter");// 默认参数
            Map<String, String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
            String token  = paramMap.get("token");// 账户名
            String notify_url = paramMap.get("notify_url");//回调地址
            String appSecret = paramMap.get("appSecret");
    		String param = appSecret+"mobile="+mobile+"&notify_url="+notify_url+"&p_id="+p_id+"&token="+token+appSecret;
            String sign = string2MD5(param);
    		JsonObject data = new JsonObject();
    		data.addProperty("c_id", c_id);
    		data.addProperty("mobile", mobile);
    		data.addProperty("notify_url", notify_url);
    		data.addProperty("p_id", p_id);
    		data.addProperty("token", token);
    		data.addProperty("sign", sign);// 设置签名
    		String params =
                    "c_id=" + c_id + "&mobile=" + mobile + "&notify_url=" + notify_url + "&p_id=" + p_id + "&token="
                        + token + "&sign=" + sign;
    		String contentType = "application/x-www-form-urlencoded";
    		
    		String postUrl = linkUrl+"/charge";
    		String retMsg = ToolHttp.post(false, postUrl,params, contentType);
            // 判断是否成功
            if (retMsg != null)
            {
                JSONObject jObject = JSONObject.parseObject(retMsg);
                String resultCode = jObject.getString("code");
                String resultMsg = jObject.getString("msg");
                String result = jObject.getString("result");
                map.put("resultCode", resultCode + ":" + resultMsg);
                if ("0".equals(resultCode))
                {
                	JSONObject resultObj = JSONObject.parseObject(result);
                	String order_num = resultObj.getString("order_num");
                    map.put("providerOrderId", order_num);
                    flag = 1;
                }else{
                	flag = 0;
                }
            }
        }
        catch (ConnectTimeoutException | SocketTimeoutException e)
        {// 请求、响应超时
            flag = -1;
        }
        catch (Exception e)
        {
            log.error("华谷流量出错" + e + MapUtils.toString(order));
        }
        map.put("status", flag);
        return map;
    }
    
    /***       
     * MD5加码 生成32位md5码    
    */       
    public String string2MD5(String inStr){           
    	MessageDigest md5 = null;           
    	try{               
    		md5 = MessageDigest.getInstance("MD5");          
    	}catch (Exception e){               
    			e.printStackTrace();               
    			return "";           
    	}           
    	char[] charArray = inStr.toCharArray();     
    	byte[] byteArray = new byte[charArray.length];              
    	for (int i = 0; i < charArray.length; i++)               
    		byteArray[i] = (byte) charArray[i];           
    	byte[] md5Bytes = md5.digest(byteArray);           
    	StringBuffer hexValue = new StringBuffer();   
    	for (int i = 0; i < md5Bytes.length; i++){               
    		int val = ((int) md5Bytes[i]) & 0xff;               
    		if (val < 16)                   
    			hexValue.append("0");               
    			hexValue.append(Integer.toHexString(val));           
    		}           
    	return hexValue.toString();       
    } 

    
}
